/*
 * Ext JS Library 2.0 RC 1 Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
Loader = function() {
	var loader;
	return {
		loading : function() {
			// safari and opera have iframe sizing issue, relayout fixes it
			// if(Ext.isSafari || Ext.isOpera ){
			// layout.layout(); // chrome is not work ...
			// }
			var loading = Ext.get('loading');
			var mask = Ext.get('loading-mask');
			mask.setOpacity(1);
			mask.fadeOut({
						xy : loading.getXY(),
						width : loading.getWidth(),
						height : loading.getHeight(),
						remove : true,
						duration : 2,
						opacity : .0,
						callback : function() {
							loading.fadeOut({
										endOpacity : .0,
										duration : 0
									});

						}
					});
		}
	}
}();
Ext.EventManager.onDocumentReady(Loader.loading, Loader, true);

Ext.Desktop = function(app) {
	this.taskbar = new Ext.ux.TaskBar(app);
	this.config = null;
	this.initialConfig = null;
	var taskbar = this.taskbar;

	var desktopEl = Ext.get('x-desktop');
	var taskbarEl = Ext.get('ux-taskbar');
	var shortcuts = Ext.get('x-shortcuts');
	// var shortcuts1 = Ext.get('x-jdw-shortcuts');
	var windows = new Ext.WindowGroup();
	var activeWindow;

	function minimizeWin(win) {
		win.minimized = true;
		win.hide();
	}

	function markActive(win) {
		if (activeWindow && activeWindow != win) {
			markInactive(activeWindow);
		}
		taskbar.setActiveButton(win.taskButton);
		activeWindow = win;
		Ext.fly(win.taskButton.el).addClass('active-win');
		win.minimized = false;
	}

	function markInactive(win) {
		if (win == activeWindow) {
			activeWindow = null;
			Ext.fly(win.taskButton.el).removeClass('active-win');
		}
	}

	function removeWin(win) {
		taskbar.removeTaskButton(win.taskButton);
		win =null;
		layout();
	}

	function layout() {
		desktopEl
				.setHeight(Ext.lib.Dom.getViewHeight() - taskbarEl.getHeight());
	}
	Ext.EventManager.onWindowResize(layout);

	var rightClick = new Ext.menu.Menu({
		id : 'rightClickCont',
		items : [{
					id : 're',
					icon : 'static/images/desktop/icons/fam/table_refresh.png',
					text : '刷新',
					href : '/index.jsp'
				},  {
					id : 'lout',
					icon : 'static/images/desktop/icons/fam/rss_go.png',
					text : '退出',
					handler : handlerLogout

				}, {
					id : 'del',
					text : '回收站',
					icon : 'static/images/desktop/icon/16551879.gif',
					handler : function() {
						loadClass("Ext.ux.RecyclePanel", "recycle-win");
					}

				}]
	});

	this.layout = layout;

	this.createWindow = function(config, cls) {
		var win = new (cls || Ext.Window)(Ext.applyIf(config || {}, {
					manager : windows,
					minimizable : true,
					maximizable : true,
					autoScroll : true
					, //setZIndex: Ext.emptyFn,  
					constrainHeader : true
				}));
		win.render(desktopEl);
		win.taskButton = taskbar.addTaskButton(win);

		win.cmenu = new Ext.menu.Menu({
					items : [

					]
				});

		win.animateTarget = win.taskButton.el;

		win.on({
					'activate' : {
						fn : markActive
					},
					'beforeshow' : {
						fn : markActive
					},
					'deactivate' : {
						fn : markInactive
					},
					'minimize' : {
						fn : minimizeWin
					},
					'close' : {
						fn : removeWin
					}
				});

		layout();
		return win;
	};

	this.getManager = function() {
		return windows;
	};

	this.getWindow = function(id) {
		return windows.get(id);
	}

	this.getWinWidth = function() {
		var width = Ext.lib.Dom.getViewWidth();
		return width < 200 ? 200 : width;
	}

	this.getWinHeight = function() {
		var height = (Ext.lib.Dom.getViewHeight() - taskbarEl.getHeight());
		return height < 100 ? 100 : height;
	}

	this.getWinX = function(width) {
		return (Ext.lib.Dom.getViewWidth() - width) / 2
	}

	this.getWinY = function(height) {
		return (Ext.lib.Dom.getViewHeight() - taskbarEl.getHeight() - height)
				/ 2;
	}

	this.setBackgroundColor = function(hex) {
		if (hex) {
			Ext.get(document.body).setStyle('background-color', '#' + hex);
			this.config.styles.backgroundcolor = hex;
		}
	};

	this.setFontColor = function(hex) {
		if (hex) {
			Ext.util.CSS
					.updateRule('.ux-shortcut-btn-text', 'color', '#' + hex);
			this.config.styles.fontcolor = hex;
		}
	};

	this.setTheme = function(o) {
		if (o && o.id && o.name && o.pathtofile) {
			Ext.util.CSS.swapStyleSheet('theme', o.pathtofile);
			this.config.styles.theme = o;
		}
	};
	this.setTransparency = function(b) {
		if (String(b) != "") {
			if (b) {
				taskbarEl.addClass("transparent");
			} else {
				taskbarEl.removeClass("transparent");
			}
			this.config.styles.transparency = b
		}
	};
	this.setWallpaper = function(o) {

		if (o && o.pathtofile) {

			var notifyWin = this.showNotification({
						html : new Date() + '正在加载组件...',
						title : 'loding...'
					});

			var wp = new Image();
			wp.src = o.pathtofile;

			var task = new Ext.util.DelayedTask(verify, this);
			task.delay(500);

			this.config.styles.wallpaper = o;
		}

		function verify() {
			if (wp.complete) {
				task.cancel();

				notifyWin.setIconClass('x-icon-done');
				notifyWin.setTitle('Welcome');
				notifyWin
						.setMessage(document.getElementById('webSiteDiv').innerHTML);
				this.hideNotification(notifyWin);

				document.body.background = wp.src;
				// alert( wp.src );
			} else {
				task.delay(500);
			}
		}
	};

	this.setWallpaperPosition = function(pos) {
		if (pos) {
			if (pos === "center") {
				var b = Ext.get(document.body);
				b.removeClass('wallpaper-tile');
				b.addClass('wallpaper-center');
			} else if (pos === "tile") {
				var b = Ext.get(document.body);
				b.removeClass('wallpaper-center');
				b.addClass('wallpaper-tile');
			}
			this.config.styles.wallpaperposition = pos;
		}
	};
	this.showNotification = function(config) {
		var win = new Ext.ux.Notification(Ext.apply({
					animateTarget : taskbarEl,
					autoDestroy : true,
					hideDelay : 5000,
					html : '',
					iconCls : 'x-icon-waiting',
					title : ''
				}, config));
		win.show();

		return win;
	};

	this.hideNotification = function(win, delay) {
		if (win) {
			(function() {
				win.animHide();
			}).defer(delay || 3000);
		}
	};

	layout();

	desktopEl.on('contextmenu', function(e) {
				if (e.target.id === desktopEl.id) {
					// alert( e.target.id );
					e.stopEvent();
					rightClick.showAt(e.getXY());
				}
			}, this);

	if (shortcuts) {
		shortcuts.on('click', function(e, t) {

					if (t = e.getTarget('dt', shortcuts)) {
						e.stopEvent();
						var module = app.getModule(t.id
								.replace('-shortcut', ''));
						// alert('ok');
						if (module) {
							module.createWindow();
						}
					}
				});

		shortcuts.on('contextmenu', function(e, t) {// 声明菜单类型
					var module = null;
					if (t = e.getTarget('dt', shortcuts)) {
						e.stopEvent();
						module = app.getModule(t.id.replace('-shortcut', ''));

					}
					e.stopEvent();
					// var tt = t;

					new Ext.menu.Menu({
						id : 'rightClick',
						items : [{
									id : 'openM',
									text : '打开',
									icon : '/static/images/desktop/icon/16551851.gif',
									handler : function() {
										if (module != null)
											module.createWindow();
									}

								}]
					}).showAt(e.getXY());// 取得鼠标点击坐标，展示菜单
				});
	}
	// shortcuts 自动换行
	var btnHeight = 61;
	var btnWidth = 64;
	var btnPadding = 15;
	var col = null;
	var row = null;
	function initColRow() {
		col = {
			index : 1,
			x : btnPadding
		};
		row = {
			index : 1,
			y : btnPadding
		};
	}
	initColRow();
	function isOverflow(y) {
		if (y > (Ext.lib.Dom.getViewHeight() - taskbarEl.getHeight())) {
			return true;
		}
		return false;
	}
	this.setXY = function(item) {
		var bottom = row.y + btnHeight, overflow = isOverflow(row.y + btnHeight);

		if (overflow && bottom > (btnHeight + btnPadding)) {
			col = {
				index : col.index++,
				x : col.x + btnWidth + btnPadding
			};
			row = {
				index : 1,
				y : btnPadding
			};
		}

		Ext.fly(item).setXY([col.x, row.y]);

		row.index++;
		row.y = row.y + btnHeight + btnPadding;
	};
	this.handleUpdate = function() {
		// alert('sddsf');
		initColRow();
		// var items=shortcuts.dom.children;
		var items = Ext.query("dt", shortcuts.dom);
		for (var i = 0, len = items.length; i < len; i++) {
			this.setXY(items[i]);
		}
	}
	this.handleUpdate();
	Ext.EventManager.onWindowResize(this.handleUpdate, this, {
				delay : 500
			});
	// end shortcuts 自动换行

};

Ext.ux.NotificationMgr = {
	positions : []
};

Ext.ux.Notification = Ext.extend(Ext.Window, {
			initComponent : function() {
				Ext.apply(this, {
							iconCls : this.iconCls || 'x-icon-information',
							width : 200
							// , height: 400
							,
							autoHeight : true,
							closable : true,
							plain : false,
							draggable : false,
							bodyStyle : 'text-align:left;padding:10px;',
							resizable : false
						});
				if (this.autoDestroy) {
					this.task = new Ext.util.DelayedTask(this.close, this);
				} else {
					this.closable = true;
				}
				Ext.ux.Notification.superclass.initComponent.call(this);
			}

			,
			setMessage : function(msg) {
				this.body.update(msg);
			}

			,
			setTitle : function(title, iconCls) {
				Ext.ux.Notification.superclass.setTitle.call(this, title,
						iconCls || this.iconCls);
			}

			,
			onRender : function(ct, position) {
				Ext.ux.Notification.superclass.onRender
						.call(this, ct, position);
			}

			,
			onDestroy : function() {
				Ext.ux.NotificationMgr.positions.remove(this.pos);
				Ext.ux.Notification.superclass.onDestroy.call(this);
			}

			,
			afterShow : function() {
				Ext.ux.Notification.superclass.afterShow.call(this);
				this.on('move', function() {
							Ext.ux.NotificationMgr.positions.remove(this.pos);
							if (this.autoDestroy) {
								this.task.cancel();
							}
						}, this);
				if (this.autoDestroy) {
					this.task.delay(this.hideDelay || 5000);
				}
			}

			,
			animShow : function() {
				this.pos = 0;
				while (Ext.ux.NotificationMgr.positions.indexOf(this.pos) > -1) {
					this.pos++;
				}
				Ext.ux.NotificationMgr.positions.push(this.pos);
				this.setSize(200, 100);
				this.el
						.alignTo(
								this.animateTarget || document,
								"br-tr",
								[
										-1,
										-1
												- ((this.getSize().height + 10) * this.pos)]);
				this.el.slideIn('b', {
							duration : .7,
							callback : this.afterShow,
							scope : this
						});
			}

			,
			animHide : function() {
				Ext.ux.NotificationMgr.positions.remove(this.pos);
				this.el.ghost("b", {
							duration : 1,
							remove : true
						});
			}
		});

//Ext.Ajax.on('requestcomplete', checkUserSessionStatus, this);
//function checkUserSessionStatus(conn, response, options) {
//
//	var result = response.responseText; // 拿到结果集，此时为字符串
//	var json = Ext.util.JSON.decode(result); // 将字符串转换为json类型
//
//	if (json.success != undefined && json.success == false) {
//		Ext.MessageBox.show({
//					title : '提示信息',
//					msg : json.errText,
//					buttons : Ext.MessageBox.OK,
//					fn : denglu,
//					icon : Ext.MessageBox.WARNING
//				});
//	}
//}
